package org.iabako.client.ui.form.business.communication;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.IFrameElement;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.InitializeEvent;
import com.google.gwt.event.logical.shared.InitializeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RichTextArea;
import org.iabako.client.config.page.PageConfigEnum;
import org.iabako.client.config.page.PageEnum;
import org.iabako.client.navigation.NavigationController;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.tools.Messages;
import org.iabako.client.ui.form.AbstractForm;
import org.iabako.client.ui.layout.field.Button;
import org.iabako.client.ui.layout.field.IField;
import org.iabako.client.ui.layout.field.InputText;
import org.iabako.client.ui.layout.field.LabelText;
import org.iabako.client.ui.layout.template.Popup;
import org.iabako.client.ui.layout.widget.dialogbox.IabakoDialogBox;
import org.iabako.client.ui.layout.widget.emailpreview.EmailForm;
import org.iabako.client.ui.layout.widget.richtexttoolbar.RichTextToolbar;
import org.iabako.client.ui.layout.widget.validation.ValidationMessage;
import org.iabako.client.user.AuthenticateUserProvider;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.enumeration.TrackingType;
import org.iabako.shared.iservice.business.CommunicationServiceAsync;
import org.iabako.shared.querydefinition.columndefinition.ClientColumnEnum;
import org.iabako.shared.querydefinition.dto.QueryResultDTO;
import org.iabako.shared.tools.GenericTools;

import java.util.List;
import java.util.Map;

/**
 * Created by jose on 02/02/15.
 */
public class CommunicationForm extends AbstractForm implements EmailForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, CommunicationForm> {
    }

    protected MyUiBinder binderForm = GWT.create(MyUiBinder.class);

    protected final CommunicationServiceAsync communicationServiceAsync = CommunicationServiceAsync.Util.getInstance();
    @UiField
    Grid richTextEditor;
    @UiField
    LabelText from;
    @UiField
    LabelText to;
    @UiField
    InputText subject;
    @UiField
    Button send;
    @UiField
    LabelText seeCompleteMailVersion;

    RichTextArea richTextArea;
    RichTextToolbar toolbar;

    String titleClientsDetail;
    Map<Long, QueryResultDTO> clients;

    protected String clientCommunicationsSessionToken;

    public CommunicationForm() {
        simplePopup = true;
        setForm(binderForm, PageConfigEnum.Login, null);

        Popup.resizeToMediumPopup();

        createRichTextEditor();

        to.getLabel().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                String textClientDetails = "\n";
                for (Long idClient : clients.keySet()) {
                    textClientDetails += "- " + clients.get(idClient).getValues().get(ClientColumnEnum.name).getValue();
                    textClientDetails += " (" + clients.get(idClient).getValues().get(ClientColumnEnum.email).getValue() + ")\n";
                }
                IabakoDialogBox iabakoDialogBox = new IabakoDialogBox(titleClientsDetail, textClientDetails, true);
                iabakoDialogBox.setAvoidClosePopupCall(true);

                NavigationController.getInstance().show(iabakoDialogBox);
            }
        });

        final CommunicationForm parentForm = this;

        seeCompleteMailVersion.getLabel().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                NavigationController.getInstance().closePopup(true);
                NavigationController.getInstance().goTo(PageEnum.EmailPreview, parentForm, null);
            }
        });

        send.getButton().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                validate();
            }
        });
    }

    protected void initializeCommunication() {

        from.setLabel(AuthenticateUserProvider.getUser().getEnterprise().getEmail());

        communicationServiceAsync.getClients(clientCommunicationsSessionToken, new IabakoAsyncCallback<Map<Long, QueryResultDTO>>() {
            public void onSuccess(Map<Long, QueryResultDTO> result) {
                clients = result;
                titleClientsDetail = Messages.getLabel("communication_client_number", clients.size() + "");
                to.setLabel(titleClientsDetail);
                super.onSuccess(result);
            }
        });

    }

    private void createRichTextEditor() {

        // Create the text area and toolbar
        richTextArea = new RichTextArea();
        richTextArea.setSize("100%", "200px");
        toolbar = new RichTextToolbar(richTextArea);
        toolbar.setWidth("100%");

        // Add the components to a panel
        richTextEditor.setWidget(0, 0, toolbar);
        richTextEditor.setWidget(1, 0, richTextArea);


        richTextArea.addInitializeHandler(new InitializeHandler() {
            public void onInitialize(InitializeEvent ie) {
                IFrameElement fe = (IFrameElement)
                        richTextArea.getElement().cast();
                Style s = fe.getContentDocument().getBody().getStyle();
                s.setProperty("fontFamily", "Arial Unicode MS,Arial,sans-serif");
                s.setProperty("fontSize", "12px");
            }
        });
    }

    public String getFrom() {
        return Messages.getLabel("communication_from") + " " + from.getLabelText();
    }

    public String getSubject() {
        return Messages.getLabel("payment_request_mail_subject_label") + " " +
                (GenericTools.isEmpty(subject.getValue()) ? "" : subject.getValue());
    }

    public String getBody() {
        return richTextArea.getHTML();
    }

    public String getContentNote() {
        return null;
    }

    @Override
    protected void onLoad() {
        super.onLoad();
    }

    @Override
    protected List<IField> getMandatoryFields() {
        return null;
    }

    @Override
    protected AbstractEntity getEntity() {
        return null;
    }

    @Override
    public boolean validate() {

        if (GenericTools.isEmpty(subject.getValue())) {
            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "communication_no_subject_error");
            return false;
        }

        if (GenericTools.isEmpty(richTextArea.getText())) {
            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "communication_no_body_error");
            return false;
        }

        if (clients.size() > 50) {

            int communicationsNumber = (clients.size() / 50 + 1);
            String confirmBoxTitle = Messages.getLabel("communication_confirm_title", clients.size() + "");
            String confirmBoxText = Messages.getLabel("communication_confirm_text", clients.size() + "", communicationsNumber + "");
            String confirmOk = Messages.getLabel("communication_confirm_ok", communicationsNumber + "");

            IabakoDialogBox iabakoDialogBox = new IabakoDialogBox(confirmBoxTitle, confirmBoxText, true, confirmOk) {
                @Override
                protected void customConfirmButtonHandler() {
                    sendCommunication();
                }
            };

            iabakoDialogBox.setAvoidClosePopupCall(true);
            NavigationController.getInstance().show(iabakoDialogBox);

        } else {
            sendCommunication();
        }

        return true;
    }

    private void sendCommunication() {
        communicationServiceAsync.sendCommunication(clients, subject.getValue(), richTextArea.getHTML(), new IabakoAsyncCallback<Void>() {
            public void onSuccess(Void result) {

                AuthenticateUserProvider.getBalanceAccount().refresh();
                AuthenticateUserProvider.getTrackingPanel().refresh(TrackingType.communicationCreate);

                popup.handleClickClose();
                ValidationMessage.getFromRootPage().showSuccessMessage(Messages.getLabel("validation_communication_send_success", clients.size() + ""));

                super.onSuccess(result);
            }
        });
    }
}
